from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from typing import List, Optional
import os
import shutil
from datetime import datetime
from app.core.database import get_db
from app.core.security import get_current_active_user
from app.models.user import User
from app.models.employee import Employee
from app.models.department import Department
from app.schemas.employee import EmployeeCreate, EmployeeUpdate, EmployeeInDB
from app.utils.excel import read_employee_excel, create_employee_excel
import uuid
import pandas as pd

router = APIRouter()

# 配置
PHOTO_DIR = "static/photos"
if not os.path.exists(PHOTO_DIR):
    os.makedirs(PHOTO_DIR)

@router.post("/import", summary="批量导入员工信息")
async def import_employees(
    file: UploadFile = File(...),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """批量导入员工信息"""
    if not file.filename.endswith('.xlsx'):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="只支持.xlsx格式的Excel文件"
        )
    
    # 保存上传的文件
    temp_file = f"temp_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
    try:
        with open(temp_file, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
        
        # 读取Excel文件
        employees = read_employee_excel(temp_file)
        
        # 批量创建员工
        created_count = 0
        error_count = 0
        errors = []
        
        for emp_data in employees:
            try:
                # 如果提供了身份证号,则检查是否已存在
                if emp_data.get('id_card'):
                    if db.query(Employee).filter(Employee.id_card == emp_data['id_card']).first():
                        raise ValueError(f"身份证号 {emp_data['id_card']} 已存在")
                
                # 检查部门是否存在
                if not db.query(Department).filter(Department.id == emp_data['department_id']).first():
                    raise ValueError(f"部门ID {emp_data['department_id']} 不存在")
                
                # 创建员工
                db_employee = Employee(**emp_data)
                db.add(db_employee)
                db.commit()
                created_count += 1
                
            except Exception as e:
                error_count += 1
                errors.append(f"第 {created_count + error_count} 行: {str(e)}")
                db.rollback()
        
        return {
            "message": "导入完成",
            "created": created_count,
            "errors": error_count,
            "error_details": errors
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"导入失败: {str(e)}"
        )
    finally:
        if os.path.exists(temp_file):
            os.remove(temp_file)

@router.get("/export", summary="导出员工信息")
async def export_employees(
    name: Optional[str] = None,
    department_id: Optional[int] = None,
    status: Optional[int] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """导出员工信息"""
    # 创建基础查询
    query = db.query(Employee).join(Department, Employee.department_id == Department.id)
    
    # 添加搜索条件，使用 AND 连接
    if name:  # 如果提供了名字，添加名字条件
        query = query.filter(Employee.name == name)  # 精确匹配
    if department_id:  # 如果提供了部门ID，添加部门条件
        query = query.filter(Employee.department_id == department_id)
    if status:  # 如果提供了状态，添加状态条件
        query = query.filter(Employee.status == status)
    
    employees = query.all()
    
    # 转换为字典列表
    employee_list = []
    for emp in employees:
        emp_dict = {
            '姓名': emp.name,
            '性别': '男' if emp.gender == 1 else '女',
            '出生日期': emp.birth_date.strftime('%Y-%m-%d'),
            '手机号': emp.phone,
            '身份证号': emp.id_card or '',
            '住址': emp.address or '',
            '部门': emp.department.name,
            '职位': emp.position,
            '状态': {1: '在职', 2: '离职', 3: '试用期'}.get(emp.status, '未知'),
            '入职时间': emp.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            '紧急联系人': emp.emergency_contact or '',
            '紧急联系电话': emp.emergency_phone or '',
            '备注': emp.remark or ''
        }
        employee_list.append(emp_dict)
    
    # 创建Excel文件
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    file_name = f"employees_{timestamp}.xlsx"
    
    # 使用pandas创建Excel
    df = pd.DataFrame(employee_list)
    
    # 设置列宽
    writer = pd.ExcelWriter(file_name, engine='openpyxl')
    df.to_excel(writer, index=False, sheet_name='员工信息')
    
    # 调整列宽
    worksheet = writer.sheets['员工信息']
    for idx, col in enumerate(df.columns):
        max_length = max(
            df[col].astype(str).apply(len).max(),
            len(col)
        )
        worksheet.column_dimensions[chr(65 + idx)].width = max_length + 2
    
    writer.close()
    
    # 返回文件
    return FileResponse(
        file_name,
        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        filename=file_name
    )

@router.get("", response_model=List[EmployeeInDB], summary="获取员工列表")
async def get_employees(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取员工列表"""
    employees = db.query(Employee).offset(skip).limit(limit).all()
    
    # 添加部门名称
    for emp in employees:
        if emp.department:
            emp.department_name = emp.department.name
        else:
            emp.department_name = None
            
    return employees

@router.post("/upload-photo", summary="上传员工照片")
async def upload_photo(
    photo: UploadFile = File(...),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """上传员工照片"""
    try:
        # 检查文件类型
        if not photo.content_type.startswith('image/'):
            raise HTTPException(
                status_code=400,
                detail="只能上传图片文件"
            )
        
        # 生成唯一文件名
        file_ext = os.path.splitext(photo.filename)[1]
        file_name = f"{uuid.uuid4()}{file_ext}"
        file_path = os.path.join(PHOTO_DIR, file_name)
        
        # 保存文件
        with open(file_path, "wb") as f:
            content = await photo.read()
            f.write(content)
        
        # 返回文件URL
        photo_url = f"/static/photos/{file_name}"
        return {"url": photo_url}
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"上传照片失败: {str(e)}"
        )

@router.post("", response_model=EmployeeInDB, summary="创建员工")
async def create_employee(
    employee: EmployeeCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建新员工"""
    try:
        # 打印接收到的数据，用于调试
        print("Received employee data:", employee.model_dump())
        
        # 创建员工
        db_employee = Employee(
            name=employee.name,
            gender=employee.gender,
            birth_date=employee.birth_date,
            id_card=employee.id_card,
            phone=employee.phone,
            address=employee.address,
            department_id=employee.department_id,
            position=employee.position,
            status=employee.status,
            photo_url=employee.photo_url,
            emergency_contact=employee.emergency_contact,
            emergency_phone=employee.emergency_phone,
            remark=employee.remark
        )
        
        db.add(db_employee)
        db.commit()
        db.refresh(db_employee)
        return db_employee
        
    except Exception as e:
        db.rollback()
        print("Error creating employee:", str(e))  # 打印错误信息
        raise HTTPException(
            status_code=400,
            detail=f"创建员工失败: {str(e)}"
        )

@router.get("/{employee_id}", response_model=EmployeeInDB, summary="获取员工详")
async def get_employee(
    employee_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """根据ID获取员工详情"""
    employee = db.query(Employee).filter(Employee.id == employee_id).first()
    if not employee:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="员工不存在"
        )
    return employee

@router.put("/{employee_id}", response_model=EmployeeInDB, summary="更新员工信息")
async def update_employee(
    employee_id: int,
    employee: EmployeeUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新员工信息"""
    db_employee = db.query(Employee).filter(Employee.id == employee_id).first()
    if not db_employee:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="员工不存在"
        )
    print("原来相片地址", db_employee.photo_url)
    print("原来姓名", db_employee.name)

    # 获取更新数据
    update_data = employee.model_dump(exclude_unset=True)
    print("更新数据中的所有字段:")
    for key, value in update_data.items():
        print(f"{key}: {value}")
    
    # 如果没有提供新的照片URL，保留原有的
    if 'photo_url' not in update_data:
        update_data['photo_url'] = db_employee.photo_url

    # 更新字段
    for field, value in update_data.items():
        setattr(db_employee, field, value)
    
    try:
        db.commit()
        db.refresh(db_employee)
        return db_employee
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"更新员工信息失败: {str(e)}"
        )

@router.delete("/{employee_id}", status_code=status.HTTP_204_NO_CONTENT, summary="删除员工")
async def delete_employee(
    employee_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除员工"""
    employee = db.query(Employee).filter(Employee.id == employee_id).first()
    if not employee:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="员工不存在"
        )
    
    db.delete(employee)
    db.commit()

@router.get("/{employee_id}/photo", summary="获取员工照片")
async def get_employee_photo(
    employee_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取员工照片"""
    employee = db.query(Employee).filter(Employee.id == employee_id).first()
    if not employee or not employee.photo_url:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="照片不存在"
        )
    
    if not os.path.exists(employee.photo_url):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="照片文件不存在"
        )
    
    return FileResponse(employee.photo_url)

@router.delete("/{employee_id}/photo", status_code=status.HTTP_204_NO_CONTENT, summary="删除员工照片")
async def delete_employee_photo(
    employee_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除员工照片"""
    employee = db.query(Employee).filter(Employee.id == employee_id).first()
    if not employee or not employee.photo_url:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="照片不存在"
        )
    
    # 从URL中获取文件名
    file_name = os.path.basename(employee.photo_url)
    file_path = os.path.join(PHOTO_DIR, file_name)
    
    # 删除文件
    try:
        if os.path.exists(file_path):
            os.remove(file_path)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除文件失败: {str(e)}"
        )
    
    # 更新数据库
    employee.photo_url = None
    db.commit()
  